<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="">
        <el-breadcrumb-item
          ><div class="div1">基本配置</div></el-breadcrumb-item
        >
        <el-breadcrumb-item
          ><div class="div2">权限管理</div></el-breadcrumb-item
        >
      </el-breadcrumb>
    </div>
    <!-- 面包屑导航 teamManage -->
    <!-- 添加团队 -->
    <div class="content">
      <h3>权限组设置</h3>
      <h4>数据筛选</h4>
      <div>
        <el-form :inline="true">
          <el-form-item label="权限组">
            <el-input
              v-model="searchWord"
              size="mini"
              placeholder="请输入权限组"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              size="mini"
              plain
              @click="fetchData('search')"
              >查询</el-button
            >
            <el-button
              type="primary"
              size="mini"
              plain
              @click="fetchData('reset')"
              >重置</el-button
            ></el-form-item
          >
        </el-form>
      </div>
      <el-button
        v-if="parArray.indexOf('authorityAdd') == 1"
        size="mini"
        type="primary"
        @click="showDialog('新增权限组', 'addPermission')"
        >新增权限</el-button
      >
      <!-- <div>{{ parArray.indexOf("authorityAdd") == 1 }}{{ parArray }}</div> -->
      <lb-table
        :column="column"
        :data="permissionList"
        pagination
        :total="page.totalNum"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20, 30, 50]"
        :current-page.sync="page.currentPage"
        :page-size="page.pageSize"
        @size-change="handleSizeChange"
        @p-current-change="handleCurrentChange"
      >
      </lb-table>
    </div>
    <!-- 管理客户等级 -->

    <!-- ============================= el-dialog ============================= -->
    <el-dialog
      :title="dialog.title"
      :visible.sync="dialog.visible"
      width="30%"
      :append-to-body="true"
      :before-close="handleClose"
    >
      <div class="dialog-content">
        <div v-if="dialog.type == 'addPermission'">
          <el-form
            :model="addPermissionForm"
            :rules="addPermissionRules"
            ref="addPermissionForm"
            label-width="100px"
          >
            <el-form-item label="权限组名称" prop="name">
              <el-input v-model="addPermissionForm.name"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="dialog.type == 'editName'">
          <el-form
            :model="addPermissionForm"
            :rules="addPermissionRules"
            ref="addPermissionForm"
            label-width="100px"
          >
            <el-form-item label="权限组名称" prop="name">
              <el-input v-model="addPermissionForm.name"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div v-if="dialog.type == 'roleList'" class="roleList">
          <div class="title">
            已关联<el-badge
              :value="permissionRoleList.length"
              type="primary"
            ></el-badge>
          </div>
          <div class="list">
            <el-tag v-for="k in permissionRoleList" :key="k.index">{{
              k.name
            }}</el-tag>
          </div>
        </div>
        <el-tabs
          v-model="tabsActiveName"
          @tab-click="tabsClick"
          v-if="dialog.type == 'editPermission'"
        >
          <el-tab-pane label="权限配置" name="config">
            <el-input
              style="margin: 0 0px 20px"
              placeholder="输入关键字进行搜索"
              v-model="permissionFilterText"
            ></el-input>
            <el-tree
              ref="tree"
              :data="permission.config.list"
              :props="permission.config.defaultProps"
              :show-checkbox="true"
              node-key="id"
              highlight-current
              :filter-node-method="filterNode"
              :expand-on-click-node="false"
              :check-strictly="permission.config.checkStrictly"
            />
          </el-tab-pane>
          <el-tab-pane label="数据权限" name="data">
            <el-radio-group v-model="permission.data">
              <el-radio
                :label="item.dictId"
                :key="item.dictId"
                v-for="item in dictionaries.data_permission"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-tab-pane>
          <el-tab-pane label="销售权限" name="sale">
            <el-radio-group v-model="permission.sale">
              <el-radio
                :label="item.dictId"
                :key="item.dictId"
                v-for="item in dictionaries.sales_authority"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.visible = false">取 消</el-button>
        <el-button type="primary" @click="dialogConfirm">确 定</el-button>
      </div>
    </el-dialog>
    <!-- ============================= el-dialog end ============================= -->
  </div>
</template>

<script>
// import { FormItem } from 'element-ui';
import LbTable from '../../../components/lb-table/lb-table'
export default {
  name: 'role',
  components: { LbTable },
  data () {
    return {
      searchWord: '',
      permissionList: [],
      permissionFilterText: '',
      column: [
        { label: '权限组名称', prop: 'name' },
        {
          label: '关联角色',
          prop: 'roleLength',
          render: (h, scope) => {
            return <el-link type="primary" onClick={() => { this.showDialog('关联角色', 'roleList', scope.$index, scope.row) }}>{scope.row[scope.column.property]}</el-link>
          }
        },
        { label: '最后更新时间', prop: 'updatedTime' },
        {
          label: '操作',
          render: (h, scope) => {
            return (
              <div>
                <el-link
                  size="mini" type="primary" onClick={() => { this.showDialog('编辑', 'editName', scope.$index, scope.row) }}>编辑</el-link>
                <el-link
                  size="mini" type="primary" onClick={() => { this.showDialog('权限分配', 'editPermission', scope.$index, scope.row) }}>权限分配</el-link>
                <el-link
                  type="danger"
                  size="mini" onClick={() => { this.onDelete(scope.$index, scope.row) }}>删除</el-link>
              </div>
            )
          }
        }],
      page: { pageNo: 1, pageSize: 10, totalNum: 0, currentPage: 1 },
      dialog: { visible: false, title: "编辑", type: '' },
      addPermissionForm: { name: '', dataPermission: '', salesAuthorityId: '' },
      addPermissionRules: {
        name: [
          { required: true, message: '请输入权限组名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        dataPermission: [
          { required: true, message: '请输入数据权限', trigger: 'change' }
        ],
      },
      dictionaries: { // 字典数据
        data_permission: [],
        sales_authority: []
      },
      permissionRoleList: [],
      permission: {
        config: {
          treeFatherIds: [],
          checkStrictly: false,
          filterText: '',
          list: [],
          defaultCheckedKeys: [],
          defaultProps: {
            children: 'children',
            label: 'name'
          },
        },
        data: '',
        sale: ''
      },
      tabsActiveName: 'config',
      currentRow: {},
      parArray: [] // 按钮权限
    };
  },
  created () {
    this.fetchData()
    this.getButtonTreeDto() // 获取权限设定
  },
  watch: {
    permissionFilterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    fetchData (type) {
      if (type == 'reset') {
        this.searchWord = ''
        this.page.pageNo = 1
        this.page.pageSize = 10
        this.page.currentPage = 1
      }
      const params = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize
      }
      if (type == 'search') {
        this.page.currentPage = 1
        this.page.pageNo = 1
        params.pageNo = 1
        params.name = this.searchWord
      }
      this.$api.permissionPageList(params).then((res) => {
        res.data.list.map((e) => {
          e.roleLength = e.roleList.length
        })
        this.permissionList = res.data.list
        this.page.totalNum = res.data.totalNum
      }).catch((err) => {
        console.log(err)
      })
    },
    getButtonTreeDto () {
      // 获取权限设定
      this.limits = JSON.parse(sessionStorage.getItem('limit'))
      const params = this.limits.buttonTreeDto.filter(
        (item) => item.menuCode === 'jurisdictionCode'
      )
      params[0].buttonList.forEach((item) => {
        this.parArray.push(item.code)
      })
      console.log(this.parArray)
    },
    handleCurrentChange (currentChange) {
      this.page.pageNo = currentChange
      this.fetchData()
    },
    handleSizeChange (sizeChange) {
      this.page.pageSize = sizeChange
      this.fetchData()
    },
    // 显示  dialog
    showDialog (title, type, index, row) {
      this.dialog.visible = true;
      this.dialog.title = title;
      this.dialog.type = type
      this.currentRow = row
      if (row && row.roleList !== undefined) {
        this.permissionRoleList = row.roleList
      }
      if (type == 'editName') {
        this.addPermissionForm.name = row.name
      }
      if (type == 'addPermission') {
        this.addPermissionForm.name = ''
        this.addPermissionForm.dataPermission = ''
        this.addPermissionForm.salesAuthorityId = ''
        let dictionaries = this.dictionaries
        for (let type in dictionaries) {
          this.getDictionaries(type)
        }
      }
      if (type == 'editPermission') {
        this.getPermissionTree()
        let dictionaries = this.dictionaries
        for (let type in dictionaries) {
          // console.log(type, dictionaries[type])
          this.getDictionaries(type)
        }
      }
    },
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => { });
    },
    dialogConfirm () {
      this.$confirm('是否确认修改权限？')
        .then(_ => {
          this.dialog.visible = false
          this.setRoleUpdateAuth()
        })
        .catch(_ => { });
    },
    // 确认后判断各类操作
    dialogConfirm () {
      const type = this.dialog.type
      switch (type) {
        case 'addPermission':
          this.submitForm('addPermissionForm')
          break;
        case 'editPermission':
          this.editPermission()
          break;
        case 'editName':
          this.editName()
          break;
        case 'roleList':
          this.dialog.visible = false;
        default:
          console.log(type)
      }
    },
    // 表单验证
    submitForm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // console.log(this.addPermissionForm.name)
          this.addPermission()
          // console.log('submit!', valid, this.addPermissionForm.name);
          this.dialog.visible = false;
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addPermission () {
      let permissionForm = this.addPermissionForm
      const params = { name: permissionForm.name, dataPermission: permissionForm.dataPermission, salesAuthorityId: permissionForm.salesAuthorityId }
      this.$api.permissionAdd(params).then((res) => {
        this.addPermissionForm.name = ''
        this.addPermissionForm.dataPermission = ''
        this.addPermissionForm.salesAuthorityId = ''
        this.fetchData()
        this.$message({ type: 'success', message: '操作成功!' });
      }).catch((err) => {
        console.log(err)
      })
    },
    // 权限分配
    onDistribution (index, item) {
      this.dialogVisible = true
      console.log('权限分配', index, item, this.dialogVisible)
    },
    // 删除
    onDelete (index, item) {
      if (this.parArray.indexOf("authorityDelete") == -1) { return this.$message({ type: 'warning', message: '权限不足!' }); }
      this.$confirm('此操作将删除选中的权限组, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const data = { id: item.id }
        this.$api.permissionDelete(data).then((res) => {
          this.fetchData()
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch((err) => {
          console.log(err)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 获取字典数据
    getDictionaries (type) {
      if (this.dictionaries.data_permission.length > 0) { return }
      if (this.dictionaries.sales_authority.length > 0) { return }
      const params = { groupId: type }
      this.$api.dictionaries(params).then((res) => {
        this.dictionaries[type] = res.data
        if (type == 'sales_authority') {
          this.dictionaries[type].unshift({ dictId: "0", dictName: "无" })
          // console.log(this.dictionaries[type])
        }
      }).catch((err) => {
        console.log(err)
      })
    },
    // 编辑 权限分配
    editPermission () {
      if (this.parArray.indexOf("authorityBind") == -1) { return this.$message({ type: 'warning', message: '权限不足!' }); }
      const keyArrKey = this.$refs.tree.getCheckedKeys()
      const keyHalfKey = this.$refs.tree.getHalfCheckedKeys()
      console.log(keyArrKey, keyHalfKey)
      const permissionObj = this.permission
      // console.log('editPermission', this.permission, keyArr)
      let params = {
        id: this.currentRow.id,
        dataPermission: permissionObj.data,
        salesAuthorityId: permissionObj.sale,
        menuButtonIds: keyHalfKey.concat(keyArrKey),
      }
      this.$api.permissionBind(params).then((res) => {
        this.fetchData()
        this.$message({ type: 'success', message: '操作成功!' });
        this.dialog.visible = false;
      }).catch((err) => {
        console.log(err)
      })
    },
    // 编辑 权限 名称
    editName () {
      if (this.parArray.indexOf("authorityUpdate") == -1) { return this.$message({ type: 'warning', message: '权限不足!' }); }
      let params = { id: this.currentRow.id, name: this.addPermissionForm.name }
      this.$api.permissionUpdateName(params).then((res) => {
        this.addPermissionForm.name = ''
        this.fetchData()
        this.$message({ type: 'success', message: '操作成功!' });
        this.dialog.visible = false;
      }).catch((err) => {
        console.log(err)
      })
    },
    // 编辑 权限分配 - tabs 切换
    tabsClick (tab, event) {
      // console.log(tab, event);
    },
    //菜单权限选择 权限配置
    getPermissionTree () {
      // if (this.permission.config.list.length > 0) { return }
      // let params = { request: {} }
      this.$api.menuTreeSelect({ request: {} }).then((res) => {
        this.permission.config.list = res.data
        this.getTreeFatherId(res.data)
        // console.log(this.permission.config.treeFatherIds)
        let params = { id: this.currentRow.id }
        this.$api.permissionDetail(params).then((resDetail) => {
          // delete resDetail.data.menuButtonIds[0]
          this.permission.config.treeFatherIds.forEach(item => {
            resDetail.data.menuButtonIds.forEach((e, i) => {
              if (item == e) {
                // console.log(e, i)
                resDetail.data.menuButtonIds.splice(i, 1)
              }
            })
          })
          // console.log(resDetail.data.menuButtonIds)
          this.permission.config.list.defaultCheckedKeys = resDetail.data.menuButtonIds
          this.$refs.tree.setCheckedKeys(resDetail.data.menuButtonIds);
          // this.$refs.tree.setCheckedNodes(resDetail.data.menuButtonIds);
          // console.log('menuButtonIds', this.permission.config.list.defaultCheckedKeys)
          this.permission.data = resDetail.data.dataPermission
          this.permission.sale = resDetail.data.salesAuthorityId ? resDetail.data.salesAuthorityId : this.dictionaries.sales_authority[0].dictId
        }).catch((errDetail) => {
          console.log(errDetail)
        })
      }).catch((err) => {
        console.log(err)
      })
    },
    // 获取所有父级 ID
    getTreeFatherId (n) {
      let arr = []
      // let child = n
      n.forEach(item => {
        if (item.children) {
          arr.push(item.id)
          // this.treeFatherIds.push(item.id)
          this.getTreeFatherId(item.children)
        }
      })
      if (arr.length > 0) {
        this.permission.config.treeFatherIds = this.permission.config.treeFatherIds.concat(arr)
      }
      // return arr  //返回数
    },
    // el-tree 复选框默认选中事件 搜索过滤数据
    filterNode (value, data) {
      if (!value) return true;
      return data.name.indexOf(value) !== -1;
    },
  }
}
</script>

<style scoped lang="scss">
.div1 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb2.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
.div2 {
  margin-left: -16px;
  background: url(../../../assets/breadcrumb1.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #fff;
}
.div3 {
  margin-left: -8px;
  background: url(../../../assets/breadcrumb3.png);
  width: 120px;
  height: 30px;
  text-align: center;
  line-height: 30px;
  color: #2d7edf;
}
.content {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #ffffff;
  h3 {
    position: relative;
    margin-bottom: 20px;
    padding-left: 10px;
    &:before {
      position: absolute;
      top: 5px;
      left: 0;
      display: inline-block;
      content: "";
      width: 3px;
      height: 20px;
      background-color: #2d7edf;
    }
  }
  .el-button {
    margin-bottom: 10px;
  }
  .el-badge {
    margin-left: 10px;
  }
}
.roleList {
  border: 1px solid #f0f3fd;
  border-radius: 5px;
  .title {
    color: #333333;
    line-height: 40px;
    padding: 0 10px;
    background-color: #f0f3fd;
    .el-badge {
      margin-top: 10px;
      margin-left: 10px;
    }
  }
  .list {
    padding: 20px;
    .el-tag {
      border: 0;
      margin-right: 10px;
      margin-bottom: 10px;
    }
  }
}
.dialog-content {
  // min-height: 210px;
  .el-tree {
    max-height: 300px;
    overflow: auto;
  }
  .el-radio {
    display: block;
    margin: 8px 0;
  }
}
</style>
<style lang="scss">
.content {
  .el-link {
    margin: 0 5px;
  }
  h4 {
    padding-top: 10px;
    border-top: 1px solid #bbbbbb;
  }
}
</style>
